package net.xdclass.springboot.Filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter(urlPatterns = "/v1/*")
  public class MyFilter implements Filter {
      @Override
      public void init(FilterConfig filterConfig) throws ServletException {
          System.out.println("destroy filter");
      }

      @Override
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
              throws IOException, ServletException {
          // 请求预处理
          System.out.println("Request received");

          HttpServletRequest httpRequest = (HttpServletRequest) request;
          HttpServletResponse httpResponse = (HttpServletResponse) response;
          String userName = request.getParameter("userName");
          if("xd".equals(userName)){
              chain.doFilter(request, response);
          }else{
              httpResponse.sendRedirect("/upload.html");
              return;
          }
          // 继续处理请求
          chain.doFilter(request, response);

          // 响应后处理
          System.out.println("Response sent");
      }

      @Override
      public void destroy() {
          System.out.println("destroy");
      }
  }